<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/8
 * Time: 9:02
 */
namespace app\admin\controller;
use think\Request;
use think\Db;
use think\Response;
use app\admin\model\Method as Methods;
use think\Session;
use think\Queue;
class Method extends Common
{
    public function contribute()
    {
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page = (int)$pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }

            $where['is_del'] = array('eq', 0);
            if (isset($pagedata['title']) && $pagedata['title'] != '') {
                $where['title'] = array('like', '%' . $pagedata['title'] . '%');
            }
            if(isset($pagedata['is_pass']) && $pagedata['is_pass'] != ''){
                $where['is_pass'] = array('like','%'.$pagedata['is_pass'].'%');
            }
            $user = new Methods();
            $data = $user->getMethodList($where,$startrow, $pagesize);
            $count = $user->getMethodCount($where);
            ajax_return(config('code.success_show'), '请求成功', $data, $count);
        } else {
            return view();
        }
    }

    /*
     * 投稿内容
     */
    public function getContent()
    {
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
            $data = Db::name('method')->field("content")->where('mid',$post['id'])->find();
            $json = json_decode($data['content'],true);
            if ($data){
                return ['code'=>0,'data'=>$json];
            }else{
                return ['code'=>1];
            }
        }
    }

    /*
     * 审核通过不通过
     */
    public function methodIsPass()
    {
        if (request()->isAjax()){
            $postData = input('param.');
            $where = "mid = {$postData['id']}";
            $guide = new Methods();
            $data['is_pass'] = $postData['is_pass'];
            $data['update_time'] = date('Y-m-d H:i:s');
            $res = $guide->isPass($where,$data);
            if($res){
                if($postData['is_pass']==1){
                    //发送系统消息
                    $data = [
                        'msg_type'=>1,
                        'receive_user_id'=>$postData['uid'],
                        'msg_title' =>'攻略发表成功!',
                        'msg_content'=>'恭喜你发表的'.$postData['title'].'已通过审核，感谢你的记录分享',
                        'create_time'=>date('Y-m-d H:i:s'),
                    ];
                }else{
                    $data = [
                        'msg_type'=>1,
                        'receive_user_id'=>$postData['uid'],
                        'msg_title' =>'攻略发表失败!',
                        'msg_content'=>'很抱歉你发表的'.$postData['title'].'未通过审核，感谢你的记录分享',
                        'create_time'=>date('Y-m-d H:i:s'),
                    ];
                }

                Db::name('message')->insert($data);

                return 0;
            }else{
                return 1;
            }
        }
    }

    /*
     * 攻略列表
     */
      public function methodlist()
      {
          if (Request::instance()->isAjax()) {
              $pagedata = Request::instance()->get();
              $pagesize = $pagedata['limit'];
              $page = (int)$pagedata['page'];
              if ($page == 1) {
                  $startrow = 0;
              } else {
                  $startrow = ($page - 1) * $pagesize;
              }

              $where['a.is_del'] = array('eq', 0);
              if (isset($pagedata['title']) && $pagedata['title'] != '') {
                  $where['title'] = array('like', '%' . $pagedata['title'] . '%');
              }
               if (isset($pagedata['is_pass']) && $pagedata['is_pass'] != '') {
                $where['is_pass'] = $pagedata['is_pass'];
            }
            if (isset($pagedata['nickname']) && $pagedata['nickname'] != '') {
                  $where['nickname'] = array('like', '%' . $pagedata['nickname'] . '%');
              }
              $user = new Methods();
              $data = Db::name('method')->alias('a')->join('user u','a.uid=u.uid','left')
                  ->where($where)->limit($startrow,$pagesize)->order('mid desc')->select(); 
               if(count($data)>0){
                foreach ($data as $key => $value) {
                  //评论数  
                   $data[$key]['comment_num'] = Db::name('comment_method')
                   ->where(['is_display'=>0,'is_del'=>0,'pid'=>0,'wid'=>$value['mid']])
                   ->count();
                 }
                  //$user->getMethodPassList($where,$startrow, $pagesize);
               }
              $count =  Db::name('method')->alias('a')->join('user u','a.uid=u.uid','left')
                  ->where($where)->count();
              ajax_return(config('code.success_show'), '请求成功', $data, $count);
          } else {
              return view();
          }
      }

    public function delMethod()
    {
        if (Request::instance()->isAjax()) {
            $post = Request::instance()->post();
            $where = "mid = {$post['id']}";
            $guide = new Methods();
            $res = $guide->guideDel($where);
            if ($res) {
                ajax_return(0,'删除成功');
            } else {
                ajax_return(1,'删除失败');
            }
        }
    }

    /*
     * 是否精选
     */
    public function isSelect()
    {
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
            $res = Db::name('method')->where('mid',$post['id'])->setField('is_select',$post['is_select']);

            if ($res!==false){
                return ['code'=>1];
            }else{
                return ['code'=>2];
            }
        }
    }
    /**
     * @return array|\think\response\View
     * 是否显示
     */
    public function isShow()
    {
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
            $res = Db::name('method')->where('mid',$post['id'])->setField('is_display',$post['is_display']);

            if ($res!==false){
                return ['code'=>1];
            }else{
                return ['code'=>2];
            }
        }
    }
    /*
     * 添加发表攻略
     */
    public function addMethod()
    {
        if(Request::instance()->isAjax())
        {
            $post = Request::instance()->post();
            $post = $post['data'];
            if(!$post['content']){
                return ['code'=>1,'msg'=>'请填写攻略内容'];
            }
            if(!$post['image']){
                return ['code'=>1,'msg'=>'请上传攻略图片'];
            }
            if(!$post['view']){
                return ['code'=>1,'msg'=>'请选择景点名称'];
            }
            //处理view_name
            $tag = explode(',',$post['view']);
            $arr1= [];
            $arr2=[];
            foreach ($tag as $key=>$v){
                $arr1[$key]  = substr($v,0,strpos($v, '+'));
                $arr2[$key] = trim(strrchr($v, '+'),'+');
            }
            $tag1 = join(',',$arr1);
            $tag2 = join(',',$arr2);
            $post['uid']=Session::get('index_uid');
            $post['view_id'] = $tag1;
            $post['view_name'] = $tag2;
            $post['update_time'] = date('Y-m-d H:i:s');
            $post['create_time'] = date('Y-m-d H:i:s');
            $post['is_pass'] = 1;
            unset($post['file']);
            unset($post['view']);
            //插入到数据库
            $insert = Db::name('method')->insertGetId($post);
            if($insert){
                return ['code'=>0];
            }else{
                return ['code'=>2];
            }

        }else{
            //景点获取
            $tours = Db::name('tours')->field('tour_id,tour_name')->where('is_pass',1)->where('is_del',0)->where('is_display',0)
                    ->select();
            $this->assign('tour',$tours);
            return view();
        }
    }

    /*
     * 修改
     */
    public function editMethod()
    {
        if(Request::instance()->isAjax())
        {
            $post = Request::instance()->post();
            $post = $post['data'];
            if(!$post['content']){
                return ['code'=>2,'msg'=>'请填写攻略内容'];
            }
            if(!$post['image']){
                return ['code'=>2,'msg'=>'请上传攻略图片'];
            }
            if(!$post['view']){
                return ['code'=>2,'msg'=>'请选择景点名称'];
            }
            //处理view_name
            $tag = explode(',',$post['view']);
            $arr1= [];
            $arr2=[];
            foreach ($tag as $key=>$v){
                $arr1[$key]  = substr($v,0,strpos($v, '+'));
                $arr2[$key] = trim(strrchr($v, '+'),'+');
            }
            $tag1 = join(',',$arr1);
            $tag2 = join(',',$arr2);
            $post['view_id'] = $tag1;
            $post['view_name'] = $tag2;
            unset($post['file']);
            unset($post['view']);
            //插入到数据库
            $insert = Db::name('method')->where('mid',Session::get('method_id'))->update($post);
            if($insert){
                Session::set('method_id',null);
                return ['code'=>0];
            }else{
                return ['code'=>2,'msg'=>'修改失败'];
            }

        }else{
            $id = input('id','','trim');
            Session::set('method_id',$id);
            //查询数据
            $data = Db::name('method')->where('mid',$id)->find();
            //查询所有景点
            $tours = Db::name('tours')->field('tour_id,tour_name')->where('is_pass',1)->where('is_del',0)->where('is_display',0)
                ->select();
            $join = explode(',',$data['view_id']);
            foreach($tours as $k=>$v){
                $tours[$k]['is_check'] = 0;
                foreach($join as $key=>$value){
                    if($v['tour_id']==$value){
                        $tours[$k]['is_check'] = 1;
                    }
                }
            }
            $this->assign('tour', $tours);
            //处理图片
            $image = explode(',', $data['image']);
            $this->assign('image', $image);
            $this->assign('data', $data);

            return view();
        }
    }

    //修改
    public function updateMethod()
    {
        if (Request::instance()->isAjax()) {
            $post = Request::instance()->post();
            $saveData = array(
              //  'set_like_num' => $post['data']['set_like_num'],
               // 'set_collect_num' => $post['data']['set_collect_num'],
                'set_share_num' => $post['data']['set_share_num'],
            );
//            $data = [];
//            for($i=0;$i<$post['data']['set_like_num'];$i++){
//                $res = Db::name('user')->field('uid')->orderRaw('rand()')->limit(1)->select();
//                $data[] = [
//                    'uid'=>$res[0]['uid'],
//                    'object_id'=>$post['data']['id'],
//                    'type'=>1,
//                    'is_read'=>0,
//                    'send_user'=>$post['data']['uid'],
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//            }
            // Db::name('log_like')->insertAll($data);

            $res = Db::name('method')->where('mid', $post['data']['id'])->update($saveData);

            if ($res !== false) {
                return ['code' => 0];
            } else {
                return ['code' => 1];
            }
        }
    }

    /*
     * 添加假点赞数
     */
    public function editLike()
    {
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
           // ini_set('max_execution_time', '0');//设置永不超时，无限执行下去直到结束
//            for($i=0;$i<$post['data']['set_like_num'];$i++){
//                $res = Db::name('user')->field('uid')->orderRaw('rand()')->limit(1)->select();
//                $data = [
//                    'uid'=>$res[0]['uid'],
//                    'object_id'=>$post['data']['id'],
//                    'type'=>1,
//                    'is_read'=>0,
//                    'send_user'=>$post['data']['uid'],
//                    'create_time'=>date('Y-m-d H:i:s')
//                ];
//                sleep(2);
//               $res =  Db::name('log_like')->insert($data);
//            }
//            if ($res !== false) {
//                return ['code' => 0];
//            } else {
//                return ['code' => 1];
//            }

//            $start_time = strtotime($post['data']['time']);
//            $end_time = strtotime($post['data']['end_time']);
//            //时间段内的平均数
//            $time = floor(($end_time-$start_time)/$post['data']['set_like_num']);
//            if($start_time<time()){
//                $start_time = 0;
//            }else{
//                $start_time = time()-$start_time;
//            }
//            $z_time = $start_time+($time*0)+mt_rand(100,800);
//            var_dump($z_time);

            for($i=0;$i<$post['data']['set_like_num'];$i++) {

                Db::startTrans();
                $res = Db::name('user')->field('uid')->orderRaw('rand()')->limit(1)->select();
                try {
                    $jobHandlerClassName = 'app\api\job\Like';
                    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                    $jobQueueName = "like";
                    // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
                    //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
                    $jobData = [
                        'uid' => $res[0]['uid'],
                        'object_id' => $post['data']['id'],
                        'send_user' => $post['data']['uid'],
                        'type'=>1
                    ];
                    $start_time = strtotime($post['data']['time']);
                    $end_time = strtotime($post['data']['end_time']);

                    //时间段内的平均数
                    $time = floor(($end_time-$start_time)/$post['data']['set_like_num']);
                    if($start_time<time()){
                        $start_time = 0;
                    }else{
                        $start_time = $start_time-time();
                    }
                    $z_time = $start_time+($time*$i)+mt_rand(60,120);
                    // 4.将该任务推送到消息队列，等待对应的消费者去执行
                    $isPushed = Queue::later($z_time,$jobHandlerClassName, $jobData, $jobQueueName);
                    // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
                    if ($isPushed !== false) {
                        Db::commit();

                    } else {
                        Db::rollback();

                    }
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
            return ['code' => 0];

        }
    }

     
     /**
      * [addMethodFalseApp 添加虚假评论]
      * @Author   kendy
      * @DateTime 2020-04-22T16:24:25+0800
      */
    public function addMethodFalseApp()
    {
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post(); 
            for($i=0;$i<$post['data']['set_comment_num'];$i++) {

                Db::startTrans();
                $res = Db::name('user')->field('uid')->where(['is_real'=>0])->orderRaw('rand()')->limit(1)->select();
                try {
                    $jobHandlerClassName = 'app\api\job\addFalseApp';
                    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                    $jobQueueName = "addfalseapp";
                    // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
                    //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
                    $jobData = [
                        'uid' => $res[0]['uid'],
                        'object_id' => $post['data']['id'],
                        'send_user' => $post['data']['uid'],
                        'type'=>1
                    ];
                    $start_time = strtotime($post['data']['starttime']);
                    $end_time = strtotime($post['data']['endtime']);

                    //时间段内的平均数
                    $time = floor(($end_time-$start_time)/$post['data']['set_comment_num']);
                    if($start_time<time()){
                        $start_time = 0;
                    }else{
                        $start_time = $start_time-time();
                    }
                    $z_time = $start_time+($time*$i)+mt_rand(60,120);
                    // 4.将该任务推送到消息队列，等待对应的消费者去执行
                    $isPushed = Queue::later($z_time,$jobHandlerClassName, $jobData, $jobQueueName);
                    // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
                    if ($isPushed !== false) {
                        Db::commit();

                    } else {
                        Db::rollback();

                    }
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
            return ['code' => 0];

        }
    }

}


 